package com.guoxianwei.scm.web.actions.grid;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SessionScope;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;

import com.google.gson.reflect.TypeToken;
import com.guoxianwei.scm.service.GridQueryService;
import com.guoxianwei.scm.web.actions.AbstractActionBean;
import com.guoxianwei.util.GSONUtils;
import com.guoxianwei.util.Page;

@SessionScope
public class GridActionBean extends AbstractActionBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2956873822076471289L;

	private  static final  String START = "start";
	private  static final  String END = "end";
	private  static final  String RULES = "rules";


	@SpringBean
	private transient GridQueryService gridQueryService;

	private Page page;

	private String where;

	private String view;

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public String getWhere() {
		return where;
	}

	public void setWhere(String where) {
		this.where = where;
	}

	public String getView() {
		return view;
	}

	public void setView(String view) {
		this.view = view;
	}
    @DefaultHandler
	public Resolution queryGrid() throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put(START, Integer.valueOf(page.getStartRow()));
		param.put(END, Integer.valueOf(page.getEndRow()));
		if (where != null) {
			this.fromWhere(param, where);
		}
		Object outPram = gridQueryService.service(view, param);
		String jsonStr = GSONUtils.toJson(outPram, false);
		return new StreamingResolution("text", new StringReader(jsonStr));
	}
    private void fromWhere(Map<String, Object> param,String where){
		Map<String,List<Map<String,Object>>> map = GSONUtils.fromJson(where, new TypeToken<Map<String,List<Map<String,Object>>>>(){});
		List<Map<String,Object>> list = map.get(RULES);
		if(list!=null){
			for(Map<String,Object> map2:list){
				param.putAll(map2);
			}
		}
    }
}
